package com.ds.lens.data.service.esservice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.Optional;

/**
 * @author ethan
 */
public abstract class AbstractIndexOperateService<T> implements IndexOperateService<T> {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Iterable<T> save(Iterable<T> entities) {
        return getIndexRepository().saveAll(entities);
    }

    @Override
    public Page<T> searchDetail(SearchQuery query) {
        return getIndexRepository().search(query);
    }

    @Override
    public AggregatedPage<T> searchAggregation(SearchQuery query) {
        return elasticsearchTemplate.queryForPage(query, getIndexClass());
    }

    public Optional<T> searchById(String id) {
        return getIndexRepository().findById(id);
    }

    @Override
    public AggregatedPage<T> searchAggregation(SearchQuery query, SearchResultMapper mapper) {
        return elasticsearchTemplate.queryForPage(query, getIndexClass(), mapper);
    }

    protected abstract Class<T> getIndexClass();

    protected abstract ElasticsearchRepository<T, String> getIndexRepository();

}
